module CsrFile(
	input		  clk,
	input		  reset,
	input  [11:0] raddr,
	output [31:0] rdata,
	input		  wen,
	input  [11:0] waddr,
	input  [31:0] wdata,

	//special port
	input		  ecall,
	input  [31:0] cause,
	input  [31:0] epc,
	output [31:0] tvec
);

//最好不要用rf的形式来创建csr_reg
reg [31:0] mcause,mepc,mtvec,mstatus;//machine-mode

wire   w_mcause,w_mepc,w_mtvec,w_mstatus; 
assign w_mcause  = waddr == 12'h342;
assign w_mepc 	 = waddr == 12'h341;
assign w_mtvec 	 = waddr == 12'h305;
assign w_mstatus = waddr == 12'h300;

always @(posedge clk) begin
	if(reset) begin
		mcause	<= 32'b0;
		mepc	<= 32'b0;
		mtvec	<= 32'b0;
		mstatus <= 32'h1800;
	end else if(ecall) begin
		mcause  <= cause;
		mepc	<= epc;
	end else if(wen) begin
 
		if(w_mcause) begin
			mcause 	<= wdata;
		end else if(w_mepc) begin
			mepc 	<= wdata;
		end else if(w_mtvec) begin
			mtvec 	<= wdata;	
		end else if(w_mstatus) begin
			mstatus <= wdata;	
		end else begin
			$display("V_WARN[csr write error]");
		end
	
	end

end

assign rdata = raddr == 12'h342 ? mcause  : 
			   raddr == 12'h341 ? mepc 	  :
			   raddr == 12'h305 ? mtvec   :
			   raddr == 12'h300 ? mstatus : 32'h0;
			
assign tvec	= ecall ? mtvec : 32'h0; 
endmodule
